import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner';

/**
 * Generated class for the QrsannerPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

// @IonicPage()
@Component({
  selector: 'page-qrsanner',
  templateUrl: 'qrsanner.html',
})
export class QrsannerPage {
  private frontCamera: boolean = false;
  private light: boolean = false;
  constructor(public navCtrl: NavController, public navParams: NavParams, private qrScanner: QRScanner,

    private alert: AlertController
  ) {
  }

  ionViewDidLoad() {
    this.qrScanner.prepare()
      .then((status: QRScannerStatus) => {

        console.log(JSON.stringify(status));

        if (status.authorized) {
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            // alert(text);
            let alet = this.alert.create({
              title: text
            })
            alet.present()
            this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
          });
          this.qrScanner.show();

        } else if (status.denied) {
        } else {
        }
      })
      .catch((e: any) => {
        let alet = this.alert.create({
          title: e
        })
        alet.present()
      });
  }

  toggleLight() {
    this.light = !this.light;
    if (this.light) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();

    }
  }

  toggleCamera() {
    this.frontCamera = !this.frontCamera;
    if (this.frontCamera) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
  }

}
